﻿using B.S.BasicData.API.Write.Application.Command.Role;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.API.Write.Application.Handler.Role
{
    /// <summary>
    /// 根据用户Id以及角色Id删除当前用户的角色信息请求命令处理类
    /// </summary>
    public class DeleteUserRoleByUserIdHandler:IRequestHandler<DeleteUserRoleByUserIdCommand,ApiResult<int>>
    {
        IBaseRepository<UserRoleModel> userRoleRep;

        public DeleteUserRoleByUserIdHandler(IBaseRepository<UserRoleModel> userRoleRep)
        {
            this.userRoleRep = userRoleRep;
        }

        public Task<ApiResult<int>> Handle(DeleteUserRoleByUserIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var userrole = userRoleRep.GetAll().Where(x => x.UserId == request.userId && x.RoleId == request.roleId && !x.IsDeleted).FirstOrDefault();

                if (userrole == null)
                {
                    res.Msg = "此用户没有角色";
                    res.Code=ApiEnum.Fail;
                    return Task.FromResult(res);
                }

                userrole.IsDeleted= true;
                int r=userRoleRep.UpdateAsync(userrole).Result;
                if (r>0)
                {
                    res.Msg = "此用户已移除当前角色";
                    res.Code = ApiEnum.Success;
                    res.Data = r;
                }
                else
                {
                    res.Msg = "移除失败";
                    res.Code = ApiEnum.Success;
                }
                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
